package my.peerencrypt.utils;

import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.log4j.Logger;


public class DataSourceManager {
	/**
	 * 默认配置文件路径
	 */
	private static String DEFAULT_CONFIG_FILE = "/dataSource.properties";
	/**
	 * 
	 */
	private static final String DATA_SOURCE_PREFIX = "my.peerencrypt.";
	/**
	 * 
	 */
	private Properties prop = new Properties();
	/**
	 * 
	 */
	private static final Logger logger = Logger.getLogger(DataSourceManager.class);
	/**
	 * 
	 */
	private Map<String ,DataSource> dataSourceMap = new HashMap<String ,DataSource>();
	/**
	 * 
	 */
	private static Map<String,DataSourceManager> dmMap = new HashMap<String,DataSourceManager>();
	static{
		Collections.synchronizedMap(dmMap);
		DataSourceManager dm = new DataSourceManager(DEFAULT_CONFIG_FILE);
		dmMap.put(DEFAULT_CONFIG_FILE, dm);
	}
	
	public static DataSourceManager getInstance(){
		return getInstance(DEFAULT_CONFIG_FILE);
	}
	public static DataSourceManager getInstance(String configFile){
		DataSourceManager dm = dmMap.get(configFile);
		if( dm != null){
			return dm;
		}else{
			 dm = new DataSourceManager(configFile);
			dmMap.put(configFile,dm);
			return dm;
		}
	}
	private DataSourceManager(String configFile){
		if(configFile==null)throw new IllegalArgumentException("configFile path is null");
		if(configFile.indexOf("/")<0)configFile="/"+configFile;
			InputStream in = DataSourceManager.class.getResourceAsStream(configFile);
			try {
				prop.load(in);
				in.close();
			} catch (Exception e) {
				logger.error("read data source config file["+configFile+"] error.", e);
				e.printStackTrace();
			}
			
	}
	public DataSource getDataSource(String dataSourceName){
			DataSource ds = dataSourceMap.get(dataSourceName);
			if(ds==null){
				String url = prop.getProperty(DATA_SOURCE_PREFIX+dataSourceName+".URL");
				String user = prop.getProperty(DATA_SOURCE_PREFIX+dataSourceName+".user");
				String password = prop.getProperty(DATA_SOURCE_PREFIX+dataSourceName+".password");
				String driver = prop.getProperty(DATA_SOURCE_PREFIX+dataSourceName+".driver");
				if(url==null || user==null || password==null || driver==null){
					logger.info("没有相应的数据源配置");
				}else{
					ds = new SimpleDataSource(driver,url,user,password);
					dataSourceMap.put(dataSourceName, ds);
				}
			}
			return ds;
	}
}
